set -e

build(){
    yum install bzip2 readline-devel zlib zlib-devel -y ||
        apt install -y sudo gcc make bzip2 libreadline-dev zlib1g zlib1g-dev	

    VER="${VER:=15.4}"
    PORT="${PORT:=5432}"

    [ -e "/usr/local/pgsql/bin/postgres" ] || [ -e "postgresql-$VER" ]  || {
        wget https://ftp.postgresql.org/pub/source/v$VER/postgresql-$VER.tar.bz2 -c -O postgresql-$VER.tar.bz2
        tar xf postgresql-$VER.tar.bz2
        cd postgresql-$VER
        ./configure --prefix=/usr/local/pgsql
        make -j 4
        make install
    }
}
 
install(){
    id -u pg || useradd pg

    [ -e "/data/db-$PORT" ] || {
    mkdir -p /data/db-$PORT
    chown -R pg /data/db-$PORT
    echo 87^KgtCKscBW > /tmp/pwfile
    sudo -u pg /usr/local/pgsql/bin/initdb -D /data/db-$PORT -U postgres -A md5 --pwfile=/tmp/pwfile
    # host port dbname, user, password
    grep "localhost:$PORT:"  ~/.pgpass || echo "localhost:$PORT:*:postgres:87^KgtCKscBW" >> ~/.pgpass
    echo 'host all all all md5' >> /data/db-$PORT/pg_hba.conf
    echo 'host replication all all md5' >> /data/db-$PORT/pg_hba.conf
    echo  listen_addresses = "'*'" >> /data/db-$PORT/postgresql.conf
    echo "port = $PORT" >> /data/db-$PORT/postgresql.conf
    chmod 0600 ~/.pgpass
    rm /tmp/pwfile
    }

    cat <<EOF > /etc/systemd/system/pg-$PORT.service
    [Unit]
    Description=pg-$PORT
    After=syslog.target network.target remote-fs.target nss-lookup.target

    [Service]
    ExecStart=/usr/local/pgsql/bin/postgres -D /data/db-$PORT
    RestartSec=10
    Restart=always
    User=pg

    [Install]
    WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable pg-$PORT
    systemctl restart pg-$PORT
    sleep 2

    # PGPASSWORD=postgres 
    /usr/local/pgsql/bin/psql -U postgres -p $PORT -c "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE' AND table_schema='public'"
}

timescaledb(){
    VER=2.14.2
    if [ ! -e "/usr/local/pgsql/lib/timescaledb.so" ]; then
        apt install cmake -y
        wget -c https://github.com/timescale/timescaledb/archive/refs/tags/$VER.tar.gz -O $VER.tar.gz
        tar xf $VER.tar.gz
        cd timescaledb-$VER
        ./bootstrap -DUSE_OPENSSL=0
        cd ./build && make
    fi
    [ -z "$PORT" ] && echo no PORT
    [ -n "$PORT" ] && {
        CONF=/data/db-$PORT/postgresql.conf
        echo $CONF
        grep timescaledb $CONF ||  echo "shared_preload_libraries = 'timescaledb'" >>  $CONF
        
        systemctl restart pg-$PORT
        sleep 1
        /usr/local/pgsql/bin/psql -U postgres -p $PORT -c "CREATE EXTENSION IF NOT EXISTS timescaledb;"
        /usr/local/pgsql/bin/psql -U postgres -p $PORT -c "\dx" | grep timescaledb || install error

    }
}

run(){
    build
    install
}

$@